import { PermissionsAndroid, Platform } from "react-native";
import { init, Geolocation } from "react-native-amap-geolocation";
import axios from "axios";
import Toast from "./Toast";

class Geo {
    // 初始化
    async initGeo() {
        // 如果是安卓，请求地理位置权限
        if (Platform.OS === "android") {
            await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION);
        }

        await init({
            // 来自于 高德地图中 android应用的key
            ios: "f27719d2c32a07a1c0060306a4593412",
            android: "f27719d2c32a07a1c0060306a4593412"
        });
        return Promise.resolve();
    }

    // 获取当前地理位置
    async getCurrentPosition() {
        return new Promise((resolve, reject) => {
            console.log("开始定位");
            Geolocation.getCurrentPosition(({ coords }) => {
                resolve(coords);
            }, reject);
        })
    }

    // 根据当前地理位置的返回值 拿到经纬度
    async getCityByLocation() {
        Toast.showLoading('努力获取中')
        const { longitude, latitude } = await this.getCurrentPosition();
        // 调用高德API
        const res = await axios.get("https://restapi.amap.com/v3/geocode/regeo", {
            // 高德地图中 web端key
            params: { location: `${longitude},${latitude}`, key: "258ea89fe866e31290f9606d1fa49855", }
        });
        Toast.hideLoading();
        return Promise.resolve(res.data);
    }
}


export default new Geo();